package com.atguigu.cart.interceptor;

import com.atguigu.cart.to.UserInfoTo;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberResponseVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.UUID;

import static com.atguigu.common.constant.CartConstant.TEMP_USER_COOKIE_NAME;
import static com.atguigu.common.constant.CartConstant.TEMP_USER_COOKIE_TIMEOUT;

/** WEB拦截器，查看用户是否登陆，
 *  *  使用购物车：
 *  *  1. 登陆了就是用用户得信息
 *  *  2. 没有登陆，就分配一个user-key
 * @Author ShiJieLin
 * @Date 2022/4/26 19:53
 * @Version 1.0
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> toThreadLocal = new ThreadLocal<>();

    /** 目标方法生效之前，给购物车分配零时user-key
     * @param request 请求对象
     * @param response 响应对象
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfoTo userInfoTo = new UserInfoTo();
        // 1.尝试获取Session的用户信息，来判断用户是否登陆
        HttpSession session = request.getSession();
        MemberResponseVo memberResponseVo = (MemberResponseVo)session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(null != memberResponseVo){
            userInfoTo.setUserId(memberResponseVo.getId());
        }
        // 2.查看cookie中是否有user-key
        Cookie[] cookies = request.getCookies();
        Arrays.stream(cookies).forEach(cookie -> {
            // user-key
            String name = cookie.getName();
            if (name.equals(TEMP_USER_COOKIE_NAME)) {
                userInfoTo.setUserKey(cookie.getValue());
                //标记为已是临时用户
                userInfoTo.setTempUser(true);
            }
        });
        // 3.如果没有 user-key，如果没有则设置一个
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            String key = UUID.randomUUID().toString();
            userInfoTo.setUserKey(key);
        }
        toThreadLocal.set(userInfoTo);
        return true;
    }

    /** 目标方法生效之后，谁知user-key cookie
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 获取当前用户的值
        UserInfoTo userInfoTo = toThreadLocal.get();

        // 如果没有临时用户一定保存一个临时用户
        if (!userInfoTo.getTempUser()) {
            // 创建一个cookie
            Cookie cookie = new Cookie(TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            // 扩大作用域
            cookie.setDomain("gulimall.com");
            // 设置过期时间
            cookie.setMaxAge(TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
